package wxb.avalon.core.controller;


import cn.hutool.http.Header;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import wxb.avalon.core.bean.Result;
import wxb.avalon.core.entity.Player;
import wxb.avalon.core.service.IPlayerService;

import javax.servlet.http.HttpServletRequest;
import java.sql.Wrapper;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wxb
 * @since 2022-01-11
 */
@Controller
@RequestMapping("/core/player")
public class PlayerController {

    @Autowired
    private IPlayerService playerService;

    @PostMapping("login")
    @ResponseBody
    public Result<Player> login(@RequestBody Player player, HttpServletRequest request){
        Result<Player>  result = new Result<>();
        try {
            if (StringUtils.isBlank(player.getName())){
                return result.fail("请输入昵称");
            }
//            player.setIp(request.getRemoteHost());
//            player.setMac(request.getHeader(Header.USER_AGENT.getValue()));
            Player oldPlayer = new Player();
            BeanUtils.copyProperties(player, oldPlayer);
            LambdaQueryWrapper<Player> playerQueryWrapper = Wrappers.lambdaQuery(player);
            playerQueryWrapper.last("limit 1");
            player = playerService.getOne(playerQueryWrapper);
            if (null == player){
                player = oldPlayer;
                playerService.save(player);
            }
            return result.ok(player);
        }catch (Exception e){
            e.printStackTrace();
            return result.fail("系统异常："+e.getLocalizedMessage());
        }
    }
}
